package org.cnc.core;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.cnc.core.MachineControl.Command;
import org.cnc.machine.CutterPosition;
import org.cnc.rmi.interfaces.MachineControlInterface;

public class MachineListener extends Thread {
		
		CutterPosition cpos = null;
		private int errCount = 0;
		
		private ChangeListener listener;
		private MachineControlInterface machine_control;
		
		public MachineListener( MachineControlInterface mci )
		{
			this.machine_control = mci;
		}
		
		public void addChangeListener( ChangeListener l )
		{
			this.listener = l;
		}
		
		@Override
		public void run()
		{
			while ( true )
			{
				try {
					CutterPosition pos = machine_control.getCutterPosition();
					
					if ( !cpos.equals(pos) )
					{
						listener.stateChanged(new ChangeEvent(Command.BACK));
						cpos = pos;
					}
				}
				catch( Exception e )
				{
					errCount++;
					
					if ( errCount > 256 )
						break;
				}
				try {
					sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}